import { Component, OnInit } from '@angular/core';
import {Login} from '../student';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {MessageService} from '../message.service';
import {Router} from '@angular/router';
import {HttpService} from "../http.service";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  login: Login = {stuid: null, password: null};
  validateForm: FormGroup;
  constructor(private httpService: HttpService,
              private fb: FormBuilder,
              private http: HttpClient,
              private message: MessageService,
              private router: Router) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      stuid: [null, [Validators.required]],
      password: [null, [Validators.required]],
      // remember: [true]
    });
  }
  submitForm() {
    for (const i of Object.keys(this.validateForm.controls)) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
  }
  checkLogin() {
    if (this.validateForm.valid) {
      this.login.stuid = this.validateForm.get('stuid').value;
      this.login.password = this.validateForm.get('password').value;
      this.httpService.httpPost(this.login).subscribe(user => {
        if (user.status === 1) {
          sessionStorage.setItem('user', this.login.stuid);
          this.message.add('登录成功');
          this.router.navigate(['home']);
        } else {
          alert('学号或密码不正确！');
          this.message.add('登录失败');
        }
      })
    }
  }
}
